/**
 * Created by Andy on 2017/5/14.
 */
import { Promise } from "es6-promise";
import { Toast } from "antd-mobile";
import { requestTimeout, baseUrl,toastShowTime } from "@/common/script/Consts";
function timeout() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("您请求网络时间过长，请重新操作");
    }, requestTimeout);
  });
}

function get(url, body) {
  return new Promise((resolve, reject) => {
    fetch(baseUrl + url, {
      credentials: "include",
      method: "get"
    })
      .then(parseJSON)
      .then(responseData => processAPICallBack(responseData, resolve, reject))
      .catch(error => {
        if (error.message == "Network request failed") {
          reject("请检查网络连接是否正常");
          return;
        }
        reject(error);
      });
  });
}

function post(url, body) {
  return new Promise((resolve, reject) => {
    fetch(baseUrl + url, {
      credentials: "include",
      method: "post",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    })
      .then(parseJSON)
      .then(responseData => processAPICallBack(responseData, resolve, reject))
      .catch(error => {
        if (error.message == "Network request failed") {
          reject("请检查网络连接是否正常");
          return;
        }
        reject(error);
      });
  });
}

function parseJSON(responseData) {
  return responseData.json();
}

function processAPICallBack(responseData, resolve, reject) {
  if (
    responseData.hasOwnProperty("status") &&
    (responseData.status == 500 || responseData.state == 500)
  ) {
    reject(responseData.message);
  } else if (
    responseData.hasOwnProperty("status") &&
    (responseData.status == 403 || responseData.state == 403)
  ) {
    reject(responseData.message);
  } else if (
    responseData.hasOwnProperty("status") &&
    (responseData.status == 4031 || responseData.state == 4031)
  ) {
    reject(responseData.message);
  } else {
    resolve(responseData);
  }
}

module.exports = {
  GET(url, body) {
    return new Promise((resolve, reject) =>
      Promise.race([timeout(), get(url, body)])
        .then(responseData => {
          resolve(responseData);
        })
        .catch(message => {
          Toast.offline(message,toastShowTime);
          reject(message);
        })
    );
  },

  POST(url, body) {
    return new Promise((resolve, reject) =>
      Promise.race([timeout(), post(url, body)])
        .then(responseData => {
          resolve(responseData);
        })
        .catch(message => {
          Toast.offline(message,toastShowTime);
          reject(message);
        })
    );
  }
};
